package slu.appli.android.wodtimera;


import slu.appli.logger.interfaces.LoggerInterface;
import slu.appli.string.format.StringFormatter;
import slu.appli.wodtimer.WodTimer;
import slu.appli.wodtimer.WodTimerException;
import slu.appli.wodtimer.command.WodTimerUIControler;
import slu.appli.wodtimer.info.WodTimerInformation;
import slu.appli.wodtimer.info.WodTimerInformationListenerInterface;
import slu.appli.wodtimer.info.logger.WodTimerInformationListenerLogger;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends Activity 
implements LoggerInterface, WodTimerInformationListenerInterface {
	private ImageButton btnStart = null;
	private ImageButton btnStop = null;
	private ImageButton btnPause = null;
	private TextView txtLog = null;
	private TextView txtRequest = null;
	private TextView txtElapse = null;
	private TextView txtDuration = null;
	private ProgressBar progressElapse = null;
	private ProgressBar progressTotal = null;
	private MenuItem mnuQuit = null;
	private MenuItem mnuSettings = null;
	private SoundPlayer soundPlayer = null;
	private long totalDuration = 0;
	
	private WodTimer wodTimer = null;
	private WodTimerUIControler controler = null;
	
	private PowerManager.WakeLock wakeLock = null;
	
	private boolean paused = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_main);
        this.txtLog = (TextView) this.findViewById(R.id.txtLog);
        this.txtRequest = (TextView) this.findViewById(R.id.txtRequest);
        this.txtElapse = (TextView) this.findViewById(R.id.txtElapse);
        this.txtDuration = (TextView) this.findViewById(R.id.txtDuration);
        this.btnStart = (ImageButton) this.findViewById(R.id.btnSTart);
        this.btnStart.setOnClickListener(new OnCLickListenerImpl());
        this.btnStop = (ImageButton) this.findViewById(R.id.btnStop);
        this.btnStop.setOnClickListener(new OnCLickListenerImpl());
        this.btnStop.setEnabled(false);
        this.btnPause = (ImageButton) this.findViewById(R.id.btnPause);
        this.btnPause.setOnClickListener(new OnCLickListenerImpl());
        this.btnPause.setEnabled(false);
        this.progressElapse = (ProgressBar) this.findViewById(R.id.progressElapse);
        this.progressTotal = (ProgressBar) this.findViewById(R.id.progressTotal);
        this.soundPlayer = new SoundPlayer(this, this);
        this.wodTimer = new WodTimer();
        this.wodTimer.setLogger(this);
        this.controler = new WodTimerUIControler(this.wodTimer);
		this.controler.setLogger(this);
		this.controler.setPlayer(this.soundPlayer);
		this.controler.addWodTimerInformationListener(new WodTimerInformationListenerLogger(this.wodTimer));
		this.controler.addWodTimerInformationListener(this);
		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		this.wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "WodTimer");
   }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        this.mnuQuit = (MenuItem) menu.findItem(R.id.menu_quit);
        this.mnuQuit.setOnMenuItemClickListener(new OnMenuItemClickListenerImpl());
        this.mnuSettings = (MenuItem) menu.findItem(R.id.menu_settings);
        this.mnuSettings.setOnMenuItemClickListener(new OnMenuItemClickListenerImpl());
        return true;
    }

    private void disablePlayerButtons() {
    	this.btnPause.setEnabled(false);
    	this.btnStart.setEnabled(false);
    	this.btnStop.setEnabled(false);
    }
    
	private class OnCLickListenerImpl implements OnClickListener {

		@Override
		public void onClick(View v) {
			if (v.equals(MainActivity.this.btnStart)) {
				try {
					if (MainActivity.this.paused)
						MainActivity.this.controler.restart();
					else {
						MainActivity.this.clear();
						MainActivity.this.totalDuration = MainActivity.this.controler.calculate(
								MainActivity.this.txtRequest.getText().toString());
						MainActivity.this.txtDuration.setText(StringFormatter.formaElapse(MainActivity.this.totalDuration));
						MainActivity.this.controler.play(MainActivity.this.txtRequest.getText().toString());
					}
				} catch (WodTimerException e) {
					MainActivity.this.addException(e);
				}
			}
			else if (v.equals(MainActivity.this.btnPause)) {
				try {
					MainActivity.this.controler.pause();
				} catch (WodTimerException e) {
					MainActivity.this.addException(e);
				}
			}
			else if (v.equals(MainActivity.this.btnStop)) {
				try {
					MainActivity.this.controler.stop();
				} catch (WodTimerException e) {
					MainActivity.this.addException(e);
				}
			}
		}
    	
    }
	
	private class OnMenuItemClickListenerImpl implements OnMenuItemClickListener {

		@Override
		public boolean onMenuItemClick(MenuItem item) {
			boolean ret = true;
			if (item.equals(MainActivity.this.mnuQuit)) {
				MainActivity.this.soundPlayer.close();
				MainActivity.this.finish();
			}
			else if (item.equals(MainActivity.this.mnuSettings)) {
				MainActivity.this.soundPlayer.play();
			}
			else ret = false;
			return ret;
		}
		
	}
	
	@Override
	public void addComment(String string) {
		this.runOnUiThread(new AddCommentUITask(string));
	}
	
	private class AddCommentUITask implements Runnable {
		private final String string;
		
		public AddCommentUITask(final String string) {
			super();
			this.string = string;
		}

		public void run() {
			MainActivity.this.txtLog.append(this.string + "\n");;
		}
	}


	@Override
	public void addException(Exception e) {
		this.runOnUiThread(new AddExceptionUITask(e));
	}
	
	private class AddExceptionUITask implements Runnable {
		private final Exception exception;
		
		public AddExceptionUITask(final Exception exception) {
			super();
			this.exception = exception;
		}

		public void run() {
			MainActivity.this.txtLog.append(this.exception.toString() + "\n");;
		}
	}

	@Override
	public void clear() {
		this.runOnUiThread(new ClearUITask());
	}
	
	private class ClearUITask implements Runnable {

		public void run() {
			MainActivity.this.txtLog.setText("");
		}
	}

	@Override
	public void WodTimerChanged(WodTimerInformation arg0) {
		this.runOnUiThread(new WodTimerChangedUITask(arg0));
	}
	
	private class WodTimerChangedUITask implements Runnable {
		private final WodTimerInformation infos;

		public WodTimerChangedUITask(WodTimerInformation infos) {
			super();
			this.infos = infos;
		}

		@Override
		public void run() {
			if (this.infos.isNewElapse()) {
				MainActivity.this.progressElapse.setProgress(0);
				MainActivity.this.progressElapse.setMax((int)(this.infos.getElapseDuration() / 1000));
			}
			else if (this.infos.isElapse()) {
				MainActivity.this.progressElapse.setProgress((int)(this.infos.getElapse() / 1000));
				MainActivity.this.progressTotal.setProgress((int)(this.infos.getDuration() / 1000));
				MainActivity.this.txtElapse.setText(StringFormatter.formaElapse(this.infos.getDuration()));
			}
			else if (this.infos.isStart() || this.infos.isRestart()) {
				MainActivity.this.progressTotal.setMax((int)(MainActivity.this.totalDuration / 1000));
				MainActivity.this.disablePlayerButtons();
				MainActivity.this.btnPause.setEnabled(true);
				MainActivity.this.btnStop.setEnabled(true);
				MainActivity.this.paused = false;
				MainActivity.this.wakeLock.acquire();
			}
			else if (this.infos.isEnd()) {
				MainActivity.this.disablePlayerButtons();
				MainActivity.this.btnStart.setEnabled(true);
				MainActivity.this.paused = false;
				MainActivity.this.wakeLock.release();
			}
			else if (this.infos.isPause()) {
				MainActivity.this.disablePlayerButtons();
				MainActivity.this.btnStop.setEnabled(true);
				MainActivity.this.btnStart.setEnabled(true);
				MainActivity.this.paused = true;
				MainActivity.this.wakeLock.release();
			}
			
		}
		
	}
}
